package com.visionblue.business.ship.util;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.util.HashMap;
import java.util.Iterator;

/**
 * @author: ysj
 * @date : 2021/3/2313:17
 * desc:
 */

public class PrinterUtil {
    private static UsbManager usbManager;
    /**
     * 满足的设备
     */
    private static UsbDevice myUsbDevice;
    /**
     * usb接口
     */
    private static UsbInterface usbInterface;
    /**
     * 块输出端点
     */
    private static UsbEndpoint epBulkOut;
    private static UsbEndpoint epBulkIn;
    /**
     * 控制端点
     */
    private static UsbEndpoint epControl;
    /**
     * 中断端点
     */
    private static UsbEndpoint epIntEndpointOut;
    private static UsbEndpoint epIntEndpointIn;
    /**
     * 连接
     */
    private static UsbDeviceConnection myDeviceConnection;

    /**
     * 初始化打印机(获取usb打印设备,连接打印机,获取USB连接权限)
     *
     * @param activity
     */
    public static void init(Activity activity) {
        //1)创建usbManager
        usbManager = (UsbManager) activity.getSystemService(Context.USB_SERVICE);
        enumeraterDevices(activity);
        getDeviceInterface();
        assignEndpoint();
    }

    /**
     * 枚举设备
     */
    private static void enumeraterDevices(Activity activity) {
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();
            //每个打印机的vendorId和productId都不同,需要自行替换
            if (device.getVendorId() == 11388 && device.getProductId() == 293) {
                myUsbDevice = device; // 获取USBDevice
                PendingIntent pi = PendingIntent.getBroadcast(activity, 0,
                        new Intent(ACTION_USB_PERMISSION), 0);
                usbManager.requestPermission(myUsbDevice, pi);
            }
        }
    }


    /**
     * 获取设备的接口
     */
    private static void getDeviceInterface() {
        if (myUsbDevice != null) {
            Log.i("------------>", "interfaceCounts : " + myUsbDevice.getInterfaceCount());
            usbInterface = myUsbDevice.getInterface(0);
            System.out.println("成功获得设备接口:" + usbInterface.getId());
        }
    }

    /**
     * 分配端点，IN | OUT，即输入输出；可以通过判断
     */
    private static void assignEndpoint() {
        if (usbInterface != null) {
            for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                UsbEndpoint ep = usbInterface.getEndpoint(i);
                switch (ep.getType()) {
                    case UsbConstants.USB_ENDPOINT_XFER_BULK://块
                        if (UsbConstants.USB_DIR_OUT == ep.getDirection()) {//输出
                            epBulkOut = ep;
                            System.out.println("Find the BulkEndpointOut," + "index:" + i + "," + "使用端点号：" + epBulkOut.getEndpointNumber());
                        } else {
                            epBulkIn = ep;
                            System.out.println("Find the BulkEndpointIn:" + "index:" + i + "," + "使用端点号：" + epBulkIn.getEndpointNumber());
                        }
                        break;
                    case UsbConstants.USB_ENDPOINT_XFER_CONTROL://控制
                        epControl = ep;
                        System.out.println("find the ControlEndPoint:" + "index:" + i + "," + epControl.getEndpointNumber());
                        break;
                    case UsbConstants.USB_ENDPOINT_XFER_INT://中断
                        if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {//输出
                            epIntEndpointOut = ep;
                            System.out.println("find the InterruptEndpointOut:" + "index:" + i + "," + epIntEndpointOut.getEndpointNumber());
                        }
                        if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                            epIntEndpointIn = ep;
                            System.out.println("find the InterruptEndpointIn:" + "index:" + i + "," + epIntEndpointIn.getEndpointNumber());
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    /**
     * 连接设备
     */
    private static void openDevice() {
        if (usbInterface != null) {//接口是否为null
            // 在open前判断是否有连接权限；对于连接权限可以静态分配，也可以动态分配权限
            UsbDeviceConnection conn = null;
            if (usbManager.hasPermission(myUsbDevice)) {
                //有权限，那么打开
                conn = usbManager.openDevice(myUsbDevice);
            }
            if (null == conn) {
                System.out.print("不能连接到设备");
                return;
            }
            //打开设备
            if (conn.claimInterface(usbInterface, true)) {
                myDeviceConnection = conn;
                if (myDeviceConnection != null)// 到此你的android设备已经连上zigbee设备
                    System.out.println("open设备成功！");
                final String mySerial = myDeviceConnection.getSerial();
                System.out.println("设备serial number：" + mySerial);
            } else {
                System.out.println("无法打开连接通道。");
                conn.close();
            }
        }
    }

    /**
     * 打印文字
     *
     * @param activity
     * @param txt
     */
    public static void printText(Activity activity, final String txt) {
        openDevice();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //每个打印机的编码格式不一样,根据打印机的编码自行修改
                    byte[] buffer = txt.getBytes("GBK");
                    myDeviceConnection.bulkTransfer(epBulkOut, buffer, buffer.length, 0);
                } catch (Exception e) {

                }
            }
        }).start();

    }

}